package com.bookstore.servlet;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;
import com.bookstore.utils.CookieUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/user.do")
public class AdminServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberme = request.getParameter("rememberme");
        Cookie usernameCookie = new Cookie("username", username);
        Cookie passwordCookie = new Cookie("password", password);
        Cookie remembermeCookie = new Cookie("rememberme", rememberme);
        usernameCookie.setPath(request.getContextPath() + "/");
        User loginUser = userService.login(new User(username, password));
        if (null != loginUser) {
            //1.把查询出来的用户信息 放入session当中
            request.getSession().setAttribute("user", loginUser);

            if (rememberme != null) {
                usernameCookie.setMaxAge(7 * 24 * 60 * 60);
                passwordCookie.setMaxAge(7 * 24 * 60 * 60);
                remembermeCookie.setMaxAge(7 * 24 * 60 * 60);
            } else {
                usernameCookie.setMaxAge(0);
                passwordCookie.setMaxAge(0);
                remembermeCookie.setMaxAge(0);
            }
            CookieUtils.addCookies(request, response, usernameCookie, passwordCookie, remembermeCookie);
            //2.跳转到主界面,添加cookie之后 再进行跳转
            response.sendRedirect(request.getContextPath() + "/admin/index.jsp");
        } else {
            //1.告诉客户端 登录失败
            //可以用ajax+swal
            //2.跳转回登录页面
            response.sendRedirect(request.getContextPath() + "/admin/login.html");
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //1.销毁session
        request.getSession().invalidate();
        //2.重定向回首页
        response.sendRedirect(request.getContextPath() + "/admin/login.html");
    }
}
